package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @title: CommonController
 * @Author 椎名真白
 * @Date: 2022-04-29 9:56
 * @Version 1.0
 */

@Slf4j
@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;
    /**
     * @description: 文件上传
     * @author: 椎名真白
     * @date: 2022-04-29 9:57
     * @return: com.itheima.reggie.common.R<java.lang.String>
     **/
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //判断basePath是否存在
        File dir = new File(basePath);
        if (!dir.exists()){
            //不存在则创建目录
            dir.mkdirs();
        }
        //获取文件的后缀 ,即文件类型
        String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //.jpg
        log.info("上传的文件类型为:{}",suffix);
        //uuid重新生成文件名 防止重复导致覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        //将临时文件持久化至指定的目录 由指定路径加上UUID创建的随机文件名构成
        file.transferTo(new File(basePath+fileName));
        return  R.success(fileName);
    }

    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //输入流读取图片
        FileInputStream fileInputStream = new FileInputStream(basePath + name);
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //IOUtils 输入流输出流对接 边读边写
        IOUtils.copy(fileInputStream,outputStream);
        fileInputStream.close();
        //return null;
    }
}
